<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>防抖和节流</title>
    <style type="text/css">
    #divEl { border: 1px solid #666; background: #ececec; width: 100px; height: 100px;}
    </style>
</head>
<body>
<h3>防抖debounce</h3>
<input type="text" id="inputEl">

<h3>节流throttle</h3>
<div id="divEl" draggable="true"></div>

<script type="text/javascript">
var inputEL = document.getElementById('inputEl')
var divEl = document.getElementById('divEl')

//防抖
function debounce(fn, delay = 500){
    let timer = null;  //闭包中的
    // console.log('parent', this, arguments)

    return function () {
        if (timer) {
            clearTimeout(timer)
        }
        const self = this;
        const args = arguments || null
        timer = setTimeout( () =>  {    //箭头函数没有自己的this值，箭头函数中所使用的this都是来自函数作用域链，这里的this指向绑定元素
            fn.apply(self, args)
            //fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}
inputEl.addEventListener('keyup', debounce(function () {
    // console.log(e)
}, 600))

function throttle(fn, delay = 100){
    let timer = null;  //闭包中的
    
    return function () {
        if (timer) {
            return
        }
        console.log(this, arguments)
        timer = setTimeout( () => {
            fn.apply(this, arguments)
            timer = null
        }, delay)
    }
}

divEl.addEventListener('drag', throttle(function (e) {
    console.log(e)
}, 200))

/*divEl.addEventListener('drag', function (e) {
    console.log(e)
})
*/

/*var obj = {
    name: 'jam',
    getName: function () {
        setTimeout( function() {
            console.log(this)
        }, 0)
    }
}

obj.getName();*/
</script>
</body>
</html>